package sale

import (
	"errors"
	"strings"
	"fmt"
	"dhfshop/models"
	"github.com/astaxie/beego/orm"
)

type SkuType struct {
	PartnerId  int64    `orm:"column(partner_id);index" json:"partner_id" form:"partner_id"`
    //ShopId     int64    `orm:"column(shop_id);index" json:"shop_id" form:"shop_id"`          /* 多店铺 */
    Id         int64  `orm:"column(id);pk;auto" json:"id" form:"id"`                       /* 编号 */
	ItemId     string `orm:"column(item_id)" json:"item_id" form:"item_id"`                /*  */
	Name       string `orm:"column(name);size(48);null" json:"name" form:"name"`           /* 名字 */
    Mark       string `orm:"column(mark);size(48);null" json:"mark" form:"mark"`           /* 备注 */
}

func init() {
    orm.RegisterModel(new(SkuType))   
}

func AddSkuType(m *SkuType) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(m)
	return
}

func AddMultiSkuTypes(list []*SkuType) (err error) {
    o := models.GetDefaultDB()
    size := len(list)
	if size > 1 {
	    _, err = o.InsertMulti(size, list) 
	}else{
	   _, err = o.Insert(list[0])
	}	
	return
}

func GetSkuTypeById(id int64) (v *SkuType, err error) {
	o := models.GetDefaultDB()
	v = &SkuType{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func GetAllSkuTypes(query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*SkuType,int64,error){
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(SkuType))
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		qs = qs.Filter(k, v)
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*SkuType
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}
	
func UpdateSkuTypeById(m *SkuType, param ...string) (err error) {
	o := models.GetDefaultDB()
	v := SkuType{Id: m.Id}
	if err = o.Read(&v); err == nil {
		_, err = o.Update(m, param...)
		return
	}
	return
}

func DeleteSkuType(id int64) (err error) {
	o := models.GetDefaultDB()
	v := SkuType{Id: id}
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&v); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}

